package pdai.a2_多线程;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestCallable implements Callable<Boolean> {
    private String url;
    private String name;

    public TestCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() throws Exception {
        webdown w = new webdown();
        w.down(url, name);
        System.out.println("下载了" + name + "文件");
        return true;
    }

    public static void main(String[] args) {
        TestCallable t1 = new TestCallable("https://iconfont.alicdn.com/t/079428b9-fba2-4450-8d9e-3e77beb7148f.png@200h_200w.jpg", "aaaaaaa.jpg");
        TestCallable t2 = new TestCallable("https://iconfont.alicdn.com/t/1570850261949.png@200h_200w.jpg", "bbbbbbb.jpg");
        TestCallable t3 = new TestCallable("https://iconfont.alicdn.com/t/4b8e539e-521f-427d-a83e-c8b94a2aab37.jpeg@200h_200w.jpg", "ccccccc.jpg");
        //创建执行服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> s1 = executorService.submit(t1);
        Future<Boolean> s2 = executorService.submit(t2);
        Future<Boolean> s3 = executorService.submit(t3);
        //关闭服务
        executorService.shutdownNow();

    }

    //下载器
    class webdown {
        public void down(String url, String name) {
            try {
                FileUtils.copyURLToFile(new URL(url), new File(name));
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("io异常，download方法异常");
            }
        }
    }
}
